package com.skz.web;

import cn.zhouyafeng.itchat4j.Wechat;
import cn.zhouyafeng.itchat4j.api.WechatTools;
import com.skz.handler.AbstractIMsgHandlerFace;
import com.skz.util.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 宋开宗
 * @create: 2019-03-11 18:47
 **/
@RestController
@RequestMapping("/login")
public class LoginController {
    @Value("${qrPath}")
    private String qrPath;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping
    public ResponseEntity login() throws InterruptedException {
        stringRedisTemplate.opsForHash().entries(RedisKey.GROUPS)
                .forEach((o, o2) -> stringRedisTemplate.opsForHash().put(RedisKey.GROUPS, o.toString(), "已失效"));
        if (WechatTools.getWechatStatus()) {
            WechatTools.logout();
        }
        new Thread(() -> {
            Wechat wechat = new Wechat(new AbstractIMsgHandlerFace() {
            }, qrPath);
            wechat.start();
        }).start();
        Thread.sleep(1000);
        return ResponseEntity.ok("请扫描二维码登录");
    }

    @GetMapping("/status")
    public boolean getStatus() {
        return WechatTools.getWechatStatus();
    }

    @GetMapping("/offline")
    public ResponseEntity offline() {
        WechatTools.logout();
        return ResponseEntity.ok("ok");
    }

}
